package com.bobo.cretrofit;

import com.bobo.cretrofit.adapter.DateAdapter;
import com.bobo.cretrofit.interceptor.BaseUrlSelectInterceptor;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.annotations.NonNull;
import okhttp3.OkHttpClient;
import retrofit2.Converter;
import retrofit2.converter.gson.GsonConverterFactory;


public abstract class ApiHandlerAdapter implements IApiHandler {
    private OkHttpClient mOkHttpClient;
    private String mBaseUrl;

    public ApiHandlerAdapter(@NotNull String baseUrl) {
        mBaseUrl = baseUrl;
    }

    @Override
    public List<Converter.Factory> buildConverterFactory() {
        Gson gson = new GsonBuilder()
                // 设置日期时间格式，另有2个重载方法
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                // 禁此序列化内部类
                .disableInnerClassSerialization()
                .disableHtmlEscaping() //禁止转义html标签
                .serializeNulls()//序列化null
                .setPrettyPrinting()//格式化输出
                .registerTypeAdapter(Date.class, new DateAdapter())
                .create();
        List<Converter.Factory> list = new ArrayList<>();
        list.add(GsonConverterFactory.create(gson));
        return list;
    }


    @NonNull
    @Override
    public OkHttpClient buildOkHttpClient() {
        if (mOkHttpClient == null) {
            mOkHttpClient = new OkHttpClient();
            OkHttpClient.Builder builder = mOkHttpClient.newBuilder()
                    .connectTimeout(8, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS);

            builder.addInterceptor(new BaseUrlSelectInterceptor(mBaseUrl));
            mOkHttpClient = builder.build();
        }
        return mOkHttpClient;
    }

    /**
     * 定义请求码是多少时，请求是成功的一般是0
     */
    @Override
    public boolean isResponseSuccess(int code) {
        return code == 0;
    }


}
